<template>
	<view class="container">
		<view class="example">
			<!--分段器-->
			<view class="uni-padding-wrap uni-common-mt" style="display: flex; justify-content: center;">
				<uni-segmented-control :current="current" :values="items" :style-type="styleType"
					:active-color="activeColor" @clickItem="onClickItem" :style="{ width: '200px'}" />
			</view>
			<view class="content">
				<!--日程列表-->
				<uni-group mode="card">
					<view>
						<uni-collapse ref="unFinishedCollapse" v-model="isUnFinishedOpen">
							<uni-collapse-item title="未完成">
								<view v-if="unfinishedCalendarList.length === 0 && finishedCalendarList.length === 0">
									<view class="no-data">暂无未完成的日程</view>
								</view>
								<view v-else-if="checkAllTaskState() === 1">
									<view class="no-data">没有日程，放松一下吧 😃</view>
								</view>
								<view v-else class="content">
									<CalendarSection :calendarList="unfinishedCalendarList" @finish-task="finishTask"
										@calendar-detail="handleCalendarClick" />
									<uni-load-more v-if="this.unfinishedCalendarList.length >= 5" :status="status"
										:content-text="contentText" @clickLoadMore="onClickLoadMore('0')" />
								</view>
							</uni-collapse-item>
						</uni-collapse>
					</view>
				</uni-group>
				<uni-group mode="card">
					<view>
						<uni-collapse ref="finishedCollapse" v-model="isFinishedOpen">
							<uni-collapse-item title="已完成">
								<view v-if="finishedCalendarList.length === 0 && unfinishedCalendarList.length === 0">
									<view class="no-data">暂无完成的日程</view>
								</view>
								<view v-else-if="checkAllTaskState() === 0">
									<view class="no-data">一件都没完成，要加油咯 😜</view>
								</view>
								<view v-else class="content">
									<CalendarSection :calendarList="finishedCalendarList"
										@calendar-detail="handleCalendarClick" />
									<uni-load-more v-if="this.finishedCalendarList.length >= 5" :status="finishedStatus"
										:content-text="finishedContentText" @clickLoadMore="onClickLoadMore('1')" />
								</view>
							</uni-collapse-item>
						</uni-collapse>
					</view>
				</uni-group>
			</view>
		</view>
		<!--新增按钮-->
		<uni-fab ref="fab" :pattern="pattern" :horizontal="horizontal" :vertical="vertical" :direction="direction"
			@fabClick="fabClick" />
	</view>
</template>

<script>
	import CalendarSection from "@/components/calendar/calendar-section.vue"
	import {
		getCalendarInfoList,
		updateCalendarInfo
	} from "@/api/todo/calendar/calendar.js"

	export default {
		components: {
			CalendarSection
		},
		data() {
			return {
				// 分段器相关
				items: ['所有', '今天', '优先级'],
				current: 1,
				activeColor: '#007aff',
				styleType: 'button',
				// 折叠面板是否展开
				isUnFinishedOpen: ['0'],
				isFinishedOpen: ['0'],
				// 折叠面板高度
				unFinishedCollapseHeight: 'auto',
				// 日程列表
				unfinishedCalendarList: [],
				finishedCalendarList: [],
				// 新增按钮相关
				horizontal: 'right',
				vertical: 'bottom',
				direction: 'horizontal',
				pattern: {
					color: '#7A7E83',
					backgroundColor: '#fff',
					selectedColor: '#007AFF',
					buttonColor: '#007AFF',
					iconColor: '#fff'
				},
				// 请求参数
				calendarInfo: {
					unfinishedPageSize: 5, // 未完成日程的初始条数
					finishedPageSize: 5, // 已完成日程的初始条数
					currentPage: 1, // 当前页码
					startTime: '',
					sortField: '1',
					sortOrder: 'ASC'
				},
				// 判断是否从其他页面返回
				isNavigatedBack: false,
				// 加载更多相关
				clickCount: 0,
				status: 'more',
				contentText: {
					contentdown: '查看更多',
					contentrefresh: '加载中',
					contentnomore: '没有更多'
				},
				finishedClickCount: 0,
				finishedStatus: 'more',
				finishedContentText: {
					contentdown: '查看更多',
					contentrefresh: '加载中',
					contentnomore: '没有更多'
				},
			}
		},
		computed: {

		},
		onLoad() {
			this.updateCalendarInfoParams();
			this.getCalendars(this.calendarInfo);
		},
		onShow() {
			// 返回页面时重新获取日程列表
			if (this.isNavigatedBack) {
				this.getCalendars(this.calendarInfo);
				this.isNavigatedBack = false; // 重置标志, 使onShow仅在页面返回时加载
			}
		},
		methods: {
			// 切换分段器
			onClickItem(index) {
				// 获取当前索引
				let i = index.currentIndex;
				this.updateCalendarInfoParams(i);
				// 还原折叠面板
				this.isUnFinishedOpen = ['0'];
				this.isFinishedOpen = ['0'];
				// 还原加载状态
				this.clickCount = 0;
				this.status = 'more';
				// 还原分页参数
				this.calendarInfo.unfinishedPageSize = 5;
				this.calendarInfo.finishedPageSize = 5;
				this.getCalendars(this.calendarInfo);
			},
			// 更新请求参数
			updateCalendarInfoParams(index = this.current) {
				let today = new Date(new Date().getTime() + 8 * 60 * 60 * 1000).toISOString().split('T')[0];
				let settings = [{
						startTime: '',
						sortField: '0',
						sortOrder: 'ASC'
					},
					{
						startTime: today,
						sortField: '1',
						sortOrder: 'ASC'
					},
					{
						startTime: '',
						sortField: '2',
						sortOrder: 'DESC'
					}
				];
				Object.assign(this.calendarInfo, settings[index]);
			},
			// 获取日程列表
			getCalendars(calendarInfo) {
				getCalendarInfoList(calendarInfo).then(response => {
					if (response.code === 200) {
						this.unfinishedCalendarList = Array.isArray(response.rows[0]['unfinished']) ?
							response.rows[0]['unfinished'] : [];
						this.finishedCalendarList = Array.isArray(response.rows[0]['finished']) ?
							response.rows[0]['finished'] : [];
						// 折叠面板微信小程序需要手动更新高度
						let self = this;
						this.$nextTick(() => {
							self.$refs.unFinishedCollapse.resize();
							self.$refs.finishedCollapse.resize();
						});
						// 判断新长度与总数是否一致
						let unfinishedTotalCount = response.rows[0]['unfinishedTotalCount'];
						let finishedTotalCount = response.rows[0]['finishedTotalCount'];
						if (this.unfinishedCalendarList.length < unfinishedTotalCount) {
							this.status = 'more';
						} else {
							this.status = 'noMore';
						};
						if (this.finishedCalendarList.length < finishedTotalCount) {
							this.finishedStatus = 'more';
						} else {
							this.finishedStatus = 'noMore';
						};
					} else {
						this.$modal.msgError(response.msg);
					}
				})
			},
			// 新增按钮点击方法
			fabClick() {
				this.$tab.navigateTo('/pages/todo/calendar/form');
				this.isNavigatedBack = true; // 设置标志
			},
			// 处理子组件传来的完成任务事件
			finishTask(calendar) {
				calendar.state = '1'; // 修改状态
				updateCalendarInfo(calendar).then(response => {
					if (response.code === 200) {
						this.$modal.msg(this.getRandomMessage(),3000);
						// 更新任务状态后重新获取日程列表
						this.getCalendars(this.calendarInfo);
					} else {
						this.$modal.msg(response.msg + ' 😫');
					}
				});
			},
			// 检查是否都是未完成 或 都是已完成的任务
			checkAllTaskState() {
				let calendarList = this.unfinishedCalendarList.concat(this.finishedCalendarList);
				if (calendarList.every(item => item.state === '0')) {
					return 0;
				}
				if (calendarList.every(item => item.state === '1')) {
					return 1;
				}
			},
			// 查看详情
			handleCalendarClick(calendarId, calendarState) {
				if (calendarState === '0') { // 未完成跳转编辑
					this.$tab.navigateTo('/pages/todo/calendar/form?calendarId=' + calendarId)
					this.isNavigatedBack = true; // 设置标志
				} else { // 已完成跳转详情
					this.$tab.navigateTo('/pages/todo/calendar/detail?calendarId=' + calendarId)
					this.isNavigatedBack = true; // 设置标志
				}
			},
			// 加载更多
			onClickLoadMore(state) {
				// 每次加载的数量
				let pageSizeIncrement = 5;
				if (state === '0') { // 未完成
					this.calendarInfo.unfinishedPageSize += pageSizeIncrement;
				} else if (state === '1') { // 已完成
					this.calendarInfo.finishedPageSize += pageSizeIncrement;
				}
				this.getCalendars(this.calendarInfo);
			},
			// 任务完成提示消息
			getRandomMessage() {
				const messages = [
					'又完成了一项任务，太棒了！继续加油哦！🎉',
					'完成了一件事，真是个小天才！继续保持！🌟',
					'干得漂亮！又向目标迈进了一步！💪',
					'完成任务，心情大好！为自己打个小call！📣',
					'今天又是成就感满满的一天，真开心！😄',
					'太厉害了，今天又有新收获！再接再厉！💖',
					'完成了一件小事，感觉自己能飞起来了！🕊️',
					'一项任务完成，给自己一个大大的赞！👍'
				];
				const randomIndex = Math.floor(Math.random() * messages.length);
				return messages[randomIndex];
			},
		}
	}
</script>

<style lang="scss">
	.example {
		padding: 15px;
		background-color: #fff;
	}

	// 列表无数据样式
	.no-data {
		text-align: center;
		color: #999;
		font-size: 14px;
		padding: 20px;
	}
</style>